package com.example.lenovo.application;

import android.content.Intent;
import android.content.IntentFilter;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {
    private Button btn1;
    private Button btn2;
    /*1.广播接受者的动态注册*/
    private MyBroadcastReceiver receiver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        /*1.广播接受者的动态注册
         * 退出后就接收不到了demob的广播
         * 两种注册不能同时生效*/
        receiver=new MyBroadcastReceiver();
        //听广播需要调到相对应的频道
        IntentFilter filter=new IntentFilter();
        filter.addAction("weather_info");
        filter.addAction("traffic_info");
        filter.addAction(Intent.ACTION_AIRPLANE_MODE_CHANGED);
        //Intent.ACTION_PACKAGE_ADDED 监控程序的安装
        filter.addAction(Intent.ACTION_PACKAGE_ADDED);
        //Intent.ACTION_MEDIA_REMOVED 监控程序的删除
        filter.addAction(Intent.ACTION_MEDIA_REMOVED);
        filter.addDataScheme("package");
        //android.net.conn.CONNECTIVITY_CHANGE:监听网络变化
        filter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
        registerReceiver(receiver,filter);

        /*1广播接受者的静态注册：在AndroidMainfest中定义
         * 退出后仍然可以接受到demob的广播*/

        /*2.广播发送*/
        //2.1.天气广播
        btn1=findViewById(R.id.btn_1);
        btn1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent=new Intent();
                intent.setAction("weather_info");
                //广播信息：晴天 25
                intent.putExtra("weather","晴天");
                intent.putExtra("wendu",25);
                sendBroadcast(intent);
                //不关心有没有人听，也不关心听不听得到
            }
        });

        //2.2.交通广播
        btn2=findViewById(R.id.btn_2);
        btn2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent=new Intent();
                intent.setAction("traffic_info");
                //广播信息：堵车 25
                intent.putExtra("traffic","堵车");
                intent.putExtra("time",25);
                sendBroadcast(intent);
            }
        });
    }
    /*3.广播接受者的注销
     * 在广播结束时必须注销（动态注册）*/
    @Override
    protected void onDestroy(){
        unregisterReceiver(receiver);
        super.onDestroy();
    }
}
